import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockDemo {

    private static int count = 0;

    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();

    // 读
    private static int read() {
        readLock.lock();
        try {
            System.out.println("read: " + count);
            return count;
        } finally {
            readLock.unlock();
        }
    }

    // 写
    private static void write() {
        writeLock.lock();
        try {
            System.out.println("write: " + (count ++));
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(ReentrantReadWriteLockDemo::read, "read-thread").start();
        new Thread(ReentrantReadWriteLockDemo::write, "write-thread").start();
    }

}
